package cn.itcast.erp.exception;

import cn.itcast.erp.controller.DepController;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.json.MappingJackson2JsonView;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * 全局异常处理
 *
 * @author 周昌洋
 * @date 2019/6/17
 */
@ControllerAdvice(basePackageClasses = DepController.class)
public class GlobalException {


    @ExceptionHandler(BindException.class)
    public ModelAndView resolveBindingException(BindException ex) {
        List<FieldError> errors = ex.getFieldErrors();
        ModelAndView mv = new ModelAndView();
        if (errors.size() != 0) {
            for (FieldError error : errors) {
                String message = error.getDefaultMessage();
                mv.addObject("message", message);
                mv.setView(new MappingJackson2JsonView());
            }
        }
        return mv;
    }
}
